{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Feature engineering on NCAA data\n",
    "\n",
    "Domain knowledge is critical to getting the best out of data analysis and machine learning.\n",
    "In the case of basketball, Dean Oliver identified four factors that are critical to success:\n",
    "* Shooting\n",
    "* Turnovers\n",
    "* Rebounding\n",
    "* Free Throws\n",
    "\n",
    "Of course, it is not enough to identify factors, you need a way to measure them.\n",
    "\n",
    "Read [this article](https://www.basketball-reference.com/about/factors.html) about the four factors and how they are measured. In this notebook, we will compute them from the box score data. The numbers are slightly different from that of the article because the article is about the NBA, but these numbers are Dean Oliver's variants for NCAA games."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Shooting efficiency\n",
    "\n",
    "Shooting is measured as the fraction of field goal attempts made, weighting 3 points higher:\n",
    "\n",
    "$(FG + 0.5 * 3P) / FGA$\n",
    "\n",
    "Let's compute the offensive and defensive shooting efficiency and see how correlated they are to winning teams.\n",
    "\n",
    "See [%%bigquery documentation](https://googleapis.github.io/google-cloud-python/latest/bigquery/magics.html) for how to use it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery df1\n",
    "SELECT \n",
    "  team_code,\n",
    "  AVG(SAFE_DIVIDE(fgm + 0.5 * fgm3,fga)) AS offensive_shooting_efficiency,\n",
    "  AVG(SAFE_DIVIDE(opp_fgm + 0.5 * opp_fgm3,opp_fga)) AS opponents_shooting_efficiency,\n",
    "  AVG(win) AS win_rate,\n",
    "  COUNT(win) AS num_games\n",
    "FROM lab_dev.team_box\n",
    "WHERE fga IS NOT NULL\n",
    "GROUP BY team_code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's remove the entries corresponding to teams that played fewer than 100 games, and then plot it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df1 = df1[df1['num_games'] > 100]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df1.plot(x='offensive_shooting_efficiency', y='win_rate', style='o');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df1.plot(x='opponents_shooting_efficiency', y='win_rate', style='o');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Does the relationship make sense? Do you think offensive and defensive efficiency are good predictors of a team's performance?\n",
    "\n",
    "It can be helpful to have a quantitive measure of the strength of the relationship. One way to measure the strength of the relationship is through the correlation. Numbers near 0 mean not correlated and numbers near +/- 1 indicate high correlation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df1.corr()['win_rate']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Turnover Percentage\n",
    "\n",
    "Turnover percentage is measured as:\n",
    "\n",
    "$TOV / (FGA + 0.475 * FTA + TOV - OREB)$\n",
    "\n",
    "As before, let's compute this, and see whether it is a good predictor. For simplicity, we will compute only offensive turnover percentage, although we should really compute both sides as we did for scoring efficiency."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rebounding\n",
    "\n",
    "Again, we'd have to measure both sides, but for simplicity, we'll do only the offensive rebounds.\n",
    "\n",
    "$ORB / (ORB + Opp DRB)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Free throw factor\n",
    "\n",
    "This is a measure of both how often a team gets to the line and how often they make them:\n",
    "\n",
    "$FT / FGA$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery df3\n",
    "SELECT \n",
    "  team_code,\n",
    "  AVG(SAFE_DIVIDE(ftm,fga)) AS freethrows,\n",
    "  AVG(win) AS win_rate,\n",
    "  COUNT(win) AS num_games\n",
    "FROM lab_dev.team_box\n",
    "WHERE fga IS NOT NULL\n",
    "GROUP BY team_code\n",
    "HAVING num_games > 100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Machine Learning\n",
    "\n",
    "Let's use these factors to create a simple ML model. Here's the dataset of features. Add the code to train the ML model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT \n",
    "  team_code,\n",
    "  is_home,\n",
    "  SAFE_DIVIDE(fgm + 0.5 * fgm3,fga) AS offensive_shooting_efficiency,\n",
    "  SAFE_DIVIDE(opp_fgm + 0.5 * opp_fgm3,opp_fga) AS opponents_shooting_efficiency,\n",
    "  SAFE_DIVIDE(tov,fga+0.475*fta+tov-oreb) AS turnover_percent,\n",
    "  SAFE_DIVIDE(opp_tov,opp_fga+0.475*opp_fta+opp_tov-opp_oreb) AS opponents_turnover_percent,\n",
    "  SAFE_DIVIDE(oreb,oreb + opp_dreb) AS rebounding,\n",
    "  SAFE_DIVIDE(opp_oreb,opp_oreb + dreb) AS opponents_rebounding,\n",
    "  SAFE_DIVIDE(ftm,fga) AS freethrows,\n",
    "  SAFE_DIVIDE(opp_ftm,opp_fga) AS opponents_freethrows,\n",
    "  win\n",
    "FROM lab_dev.team_box\n",
    "WHERE fga IS NOT NULL and win IS NOT NULL\n",
    "LIMIT 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Is this correct, though? Will we know the offensive efficiency of the team before the game is played? How do we fix it?\n",
    "\n",
    "If you are stuck, please feel free to look at the solution notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Copyright 2019 Google Inc. All Rights Reserved.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
